package cn.heyige.backend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.heyige.backend.common.CommResponse;
import cn.heyige.backend.dto.ChatHistoryDto;
import cn.heyige.backend.service.impl.ChatHistoryServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("api/chatHistory")
@Tag(name = "聊天历史", description = "聊天历史管理相关接口")
public class ChatHistoryController {

    private final ChatHistoryServiceImpl chatHistoryService;

    /**
     * 获取用户的聊天历史列表
     */
    @GetMapping
    @Operation(summary = "获取用户聊天历史", description = "分页获取用户的聊天历史记录")
    public CommResponse<IPage<ChatHistoryDto.ChatHistoryResponse>> getUserChatHistory(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "页码", example = "0") @RequestParam(defaultValue = "0") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {
        IPage<ChatHistoryDto.ChatHistoryResponse> chatHistories = chatHistoryService.getUserChatHistory(userId, page, size);
        return CommResponse.ok(chatHistories);
    }

    /**
     * 根据会话ID获取聊天历史列表
     */
    @GetMapping("/session/{sessionId}")
    @Operation(summary = "根据会话ID获取聊天历史", description = "根据会话ID分页获取聊天历史记录")
    public CommResponse<IPage<ChatHistoryDto.ChatHistoryResponse>> getChatHistoryBySession(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "会话ID", required = true, example = "session_123") @PathVariable String sessionId,
            @Parameter(description = "页码", example = "0") @RequestParam(defaultValue = "0") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {
        IPage<ChatHistoryDto.ChatHistoryResponse> chatHistories = chatHistoryService.getChatHistoryBySession(userId, sessionId, page, size);
        return CommResponse.ok(chatHistories);
    }

    /**
     * 获取用户的会话列表
     */
    @GetMapping("/sessions")
    @Operation(summary = "获取用户会话列表", description = "分页获取用户的会话列表")
    public CommResponse<IPage<ChatHistoryDto.SessionResponse>> getUserSessions(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "页码", example = "0") @RequestParam(defaultValue = "0") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {

        IPage<ChatHistoryDto.SessionResponse> sessions = chatHistoryService.getUserSessions(userId, page, size);
        return CommResponse.ok(sessions);
    }

    /**
     * 删除聊天记录
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除聊天记录", description = "删除指定的聊天记录")
    public CommResponse<Void> deleteChatHistory(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "聊天记录ID", required = true, example = "1") @PathVariable Integer id) {
        chatHistoryService.deleteChatHistory(id, userId);
        return CommResponse.ok();
    }

    /**
     * 删除会话的所有聊天记录
     */
    @DeleteMapping("/session/{sessionId}")
    @Operation(summary = "删除会话的聊天记录", description = "删除指定会话的所有聊天记录")
    public CommResponse<Void> deleteChatHistoryBySession(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "会话ID", required = true, example = "session_123") @PathVariable String sessionId) {
        chatHistoryService.deleteChatHistoryBySession(userId, sessionId);
        return CommResponse.ok();
    }

    /**
     * 删除用户的所有聊天记录
     */
    @DeleteMapping("/all")
    @Operation(summary = "删除所有聊天记录", description = "删除用户的所有聊天记录")
    public CommResponse<Void> deleteAllChatHistory(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId) {
        chatHistoryService.deleteAllChatHistory(userId);
        return CommResponse.ok();
    }

    /**
     * 清除指定时间之前的聊天记录
     */
    @DeleteMapping("/clear")
    @Operation(summary = "清除指定时间前的聊天记录", description = "清除指定时间之前的聊天记录")
    public CommResponse<Void> clearChatHistoryBeforeTime(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "清除请求参数") @Valid @RequestBody ChatHistoryDto.ClearRequest request) {
        chatHistoryService.clearChatHistoryBeforeTime(userId, request.getBeforeTime());
        return CommResponse.ok();
    }

    /**
     * 获取聊天统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取聊天统计信息", description = "获取用户的聊天统计信息")
    public CommResponse<ChatHistoryDto.StatisticsResponse> getChatStatistics(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId) {
        ChatHistoryDto.StatisticsResponse statistics = chatHistoryService.getChatStatistics(userId);
        return CommResponse.ok(statistics);
    }

    /**
     * 清除指定时间之前的聊天记录（通过URL参数）
     */
    @DeleteMapping("clearBefore")
    @Operation(summary = "清除指定时间前的聊天记录", description = "通过URL参数清除指定时间之前的聊天记录")
    public CommResponse<Void> clearChatHistoryBeforeTime(
            @Parameter(hidden = true) @RequestAttribute("userId") Integer userId,
            @Parameter(description = "清除时间点", example = "2024-01-01T00:00:00") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime beforeTime) {
        chatHistoryService.clearChatHistoryBeforeTime(userId, beforeTime);
        return CommResponse.ok();
    }
}